﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GRWL.BZSC.UI.BaseDataSvc;
using System.Collections;

namespace GRWL.BZSC.UI
{
    public partial class EditRqrtFrm : BaseFrm
    {
        /// <summary>
        /// 当前需求单类型
        /// </summary>
        public GRWL.BZSC.Common.EnumCommon.RequirementType RqrtType { get; set; }

        /// <summary>
        /// 单据ID
        /// </summary>
        int _Id { get; set; }

        /// <summary>
        /// 当前订单Id
        /// </summary>
        int? _OrderId { get; set; }
        /// <summary>
        /// 当前订单号
        /// </summary>
        string _OrderCode { get; set; }

        /// <summary>
        /// 窗体是否编辑模式
        /// </summary>
        bool _EditMode { get; set; }

        /// <summary>
        /// 临时变量日期控件
        /// </summary>
        DateTimePicker _DTP = new DateTimePicker();
        /// <summary>
        /// 临时变量绘画控件范围
        /// </summary>
        Rectangle _Rectangle { get; set; }
        /// <summary>
        /// 下拉
        /// </summary>
        ComboBox _CbBox = new ComboBox();
        ComboBox _CbBoxDept = new ComboBox();
        ComboBox _CbBoxPrjt = new ComboBox();

        Common.BillOperateType _OperateType = Common.BillOperateType.None;
        /// <summary>
        /// 操作状态
        /// </summary>
        Common.BillOperateType OperateType
        {
            get
            {
                return this._OperateType;
            }
            set
            {
                this._OperateType = value;
                initBtns();
            }
        }

        /// <summary>
        /// 单据明细临时变量
        /// </summary>
        DataTable _DTDetail { get; set; }

        /// <summary>
        /// 当前单据实体
        /// </summary>
        XRequirement _XR { get; set; }

        public EditRqrtFrm()
        {
            //this._DTP = new DateTimePicker();//这里实例化一个DateTimePicker控件
            InitializeComponent();

            this.dataGridView1.Controls.Add(this._DTP);  //把时间控件加入DataGridView
            this._DTP.Visible = false;  //先不让它显示
            this._DTP.Format = DateTimePickerFormat.Custom;
            this._DTP.TextChanged += new EventHandler(dtp_TextChange); //为时间控件加入事件dtp_TextChange            

            this._CbBoxPrjt.Visible = false;
            this._CbBoxPrjt.DropDownStyle = ComboBoxStyle.DropDownList;
            this._CbBoxPrjt.Click += new EventHandler(comBoxPrjt_Change);
            this.dataGridView1.Controls.Add(this._CbBoxPrjt);

            this._CbBoxDept.Visible = false;
            this._CbBoxDept.DropDownStyle = ComboBoxStyle.DropDownList;
            this._CbBoxDept.Click += new EventHandler(comBoxDept_Change);
            this.dataGridView1.Controls.Add(this._CbBoxDept);

            this.BaseDataProxy = new BaseDataClient();

            GRWL.BZSC.Common.EventCommon.FindMaterialUdDGVEvnt += new GRWL.BZSC.Common.EventCommon.UpdateDataGridViewDlgt(updateFindMaterial);
        }

        private void EditRqrtFrm_Load(object sender, EventArgs e)
        {
            this.BaseDataProxy.Open();
            initComboBox();
            setCellFomatting();
        }

        #region 委托回调事件
        /// <summary>
        /// 选择物料回调
        /// </summary>
        public void updateFindMaterial(object o, EventArgs arg)
        {
            CommonEventArg<QMaterial[]> argObj = (CommonEventArg<QMaterial[]>)arg;
            if (argObj != null)
            {
                foreach (QMaterial m in argObj.t)
                {
                    decimal? currentStock = this.BaseDataProxy.GetCurrentStock(m.Id);
                    XMaterial xm = this.BaseDataProxy.GetXMaterial(m.Id, null,null);
                    if (xm != null)
                    {
                        addDetailRow(null, 1, null, null, null, m.Id, m.Code, m.CnName, m.Specs, m.PrjtId, m.PrjtCode, null, 1, 1, DateTime.Now, DateTime.Now,
                        m.Source, xm.Material.department, xm.DepartmentName, currentStock, currentStock, currentStock, 1, 1, xm.CategoryName, xm.Material.unit,
                        xm.Material.isNominal, this.txtBoxCode.Text, this._Id, false, false, 1);
                    }
                }
            }
        }
        #endregion

        /// <summary>
        /// 增加单据明细
        /// </summary>
        /// <param name="detailId">需求明细Id</param>
        /// <param name="level">层数</param>
        /// <param name="orderId">订单Id</param>
        /// <param name="orderCode">订单号</param>
        /// <param name="orderDetailId">订单明细Id</param>
        /// <param name="materialId">材料Id</param>
        /// <param name="materialCode">材料号</param>
        /// <param name="materialName">材料名称</param>
        /// <param name="specs">材料规格</param>
        /// <param name="prjtId">产品工程id</param>
        /// <param name="prjtCode">产品工程号</param>
        /// <param name="memo">备注</param>
        /// <param name="hairNeeds">毛需求</param>
        /// <param name="netNeeds">净需求</param>
        /// <param name="rqrtDate">需求日期</param>
        /// <param name="releaseDate">发放日期</param>
        /// <param name="source">来源</param>
        /// <param name="departmentId">部门Id</param>
        /// <param name="departmentName">部门名称</param>
        /// <param name="currentStock">当前库存</param>
        /// <param name="safeStock">安全库存</param>
        /// <param name="availableStock">可用库存</param>
        /// <param name="planPurchase">计划采购</param>
        /// <param name="planProduction">计划生产</param>
        /// <param name="category">材料分类</param>
        /// <param name="unit">材料单位</param>
        /// <param name="isNominal">是否虚设件</param>
        /// <param name="rqrtCode">需求号</param>
        /// <param name="rqrtId">需求Id</param>
        /// <param name="isMain">主生产单</param>
        /// <param name="isRelease">发放</param>
        /// <param name="orderNum">订单数</param>
        private void addDetailRow(int? detailId, int? level, int? orderId, string orderCode, int? orderDetailId, int materialId, string materialCode, string materialName,
            string specs, int? prjtId, string prjtCode, string memo, decimal? hairNeeds, decimal? netNeeds, DateTime? rqrtDate, DateTime? releaseDate, string source,
            int? departmentId, string departmentName, decimal? currentStock, decimal? safeStock, decimal? availableStock, decimal? planPurchase, decimal? planProduction, string category,
            string unit, bool isNominal, string rqrtCode, int rqrtId, bool isMain, bool isRelease, decimal? orderNum)
        {
            string rqrtDateStr = string.Empty;
            string releaseDateStr = string.Empty;

            if (rqrtDate != null)
                rqrtDateStr = Convert.ToDateTime(rqrtDate).ToShortDateString();
            if (releaseDate != null)
                releaseDateStr = Convert.ToDateTime(releaseDate).ToShortDateString();

            int rowId = this.dataGridView1.Rows.Add(new object[] {detailId, level,orderId,orderCode,orderDetailId,materialId,materialCode,materialName,specs,
                        prjtId,prjtCode,memo,hairNeeds,netNeeds,rqrtDateStr,releaseDateStr,source,departmentId,departmentName,currentStock,safeStock,availableStock,
                        planPurchase,planProduction,category,unit,isNominal,rqrtCode,rqrtId,isMain,isRelease,orderNum});
            if (isNominal)//虚设件设置颜色
                this.dataGridView1.Rows[rowId].DefaultCellStyle.ForeColor = Color.FromArgb(255, 0, 0);
        }

        /// <summary>
        /// 设置单元格格式
        /// </summary>
        private void setCellFomatting()
        {
            this.dataGridView1.Columns[13].DefaultCellStyle.Format = "F2";//毛需求 设置格式为小数
            this.dataGridView1.Columns[13].DefaultCellStyle.NullValue = "0.00";
            this.dataGridView1.Columns[14].DefaultCellStyle.Format = "F2";//净需求 设置格式为小数
            this.dataGridView1.Columns[14].DefaultCellStyle.NullValue = "0.00";
            this.dataGridView1.Columns[15].DefaultCellStyle.Format = "d";//需求日期 设置日期格式为2000-11-1
            this.dataGridView1.Columns[16].DefaultCellStyle.Format = "d";//发放日期 设置日期格式为2000-11-1
            this.dataGridView1.Columns[20].DefaultCellStyle.Format = "F2";//当前库存 设置格式为小数
            this.dataGridView1.Columns[20].DefaultCellStyle.NullValue = "0.00";
            this.dataGridView1.Columns[21].DefaultCellStyle.Format = "F2";//安全库存 设置格式为小数
            this.dataGridView1.Columns[21].DefaultCellStyle.NullValue = "0.00";
            this.dataGridView1.Columns[22].DefaultCellStyle.Format = "F2";//当前可用库存 设置格式为小数
            this.dataGridView1.Columns[22].DefaultCellStyle.NullValue = "0.00";
            this.dataGridView1.Columns[23].DefaultCellStyle.Format = "F2";//计划采购数 设置格式为小数
            this.dataGridView1.Columns[23].DefaultCellStyle.NullValue = "0.00";
            this.dataGridView1.Columns[24].DefaultCellStyle.Format = "F2";//计划生产数 设置格式为小数
            this.dataGridView1.Columns[24].DefaultCellStyle.NullValue = "0.00";
        }

        /// <summary>
        /// 加载下拉数据
        /// </summary>
        private void initComboBox()
        {
            //this._CbBox = new ComboBox();
            this._CbBox.DropDownStyle = ComboBoxStyle.DropDownList;
            Common.BindOptionComboBox(this._CbBox, GRWL.BZSC.Common.EnumCommon.OptionType.来源类型, this.BaseDataProxy, string.Empty);
            this._CbBox.Visible = false;
            this._CbBox.SelectedIndexChanged += new EventHandler(comboBox_Change);
            this.dataGridView1.Controls.Add(this._CbBox);
        }

        private void comboBox_Change(object sender, EventArgs e)
        {
            this.dataGridView1.CurrentCell.Value = this._CbBox.Text;
        }

        private void comBoxDept_Change(object sender, EventArgs e)
        {
            DeptFrm frm = new DeptFrm();
            frm.Text = "选择部门";
            if (frm.ShowDialog() == DialogResult.OK)
            {
                if (frm.SelectorItem != null)
                {
                    this.dataGridView1.Rows[this.dataGridView1.CurrentCell.RowIndex].Cells[this.dataGridView1.CurrentCell.ColumnIndex - 1].Value = frm.SelectorItem.Value;
                    this.dataGridView1.CurrentCell.Value = frm.SelectorItem.Name;
                }
            }
        }

        private void comBoxPrjt_Change(object sender, EventArgs e)
        {
            FindPrdtPrjtFrm frm = new FindPrdtPrjtFrm(this.dataGridView1.Rows[this.dataGridView1.CurrentCell.RowIndex].Cells[5].Value.ToString());
            if (frm.ShowDialog() == DialogResult.OK)
            {
                if (frm.SelectorItem != null)
                {
                    this.dataGridView1.Rows[this.dataGridView1.CurrentCell.RowIndex].Cells[this.dataGridView1.CurrentCell.ColumnIndex - 1].Value = frm.SelectorItem.Id;
                    this.dataGridView1.CurrentCell.Value = frm.SelectorItem.Code;
                }
            }
        }

        private void dtp_TextChange(object sender, EventArgs e)
        {
            this.dataGridView1.CurrentCell.Value = this._DTP.Text.ToString();  //时间控件选择时间时，就把时间赋给所在的单元格
        }

        /// <summary>
        /// 打开单据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (this.OperateType == Common.BillOperateType.Add || this.OperateType == Common.BillOperateType.Update)
            {
                if (MessageBox.Show("你想保存所作的修改吗？", "系统提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    //保存当前编辑单据
                    save();
                }
                clearForm();
            }

            //加载打开单据
            FindBillFrm frm = new FindBillFrm();
            frm.AllowMulitSelect = false;
            frm.SelectBillType = GRWL.BZSC.Common.EnumCommon.BillType.SCXQ;
            frm.ShowDialog(this);
            if (frm.DialogResult == DialogResult.OK)
            {
                if (frm.SelectedItems != null)
                {
                    QRequirement qRqrt = OTConverter.ConvertToObject<QRequirement>(frm.SelectedItems);
                    this._Id = qRqrt.Id;
                    initEdit();
                    //已审批的单据不能修改
                    if (qRqrt.Status == GRWL.BZSC.Common.EnumCommon.VerifyStatus.已批.ToString())
                    { this.OperateType = Common.BillOperateType.View; }
                }
            }
        }

        /// <summary>
        /// 运行生产需求
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelect_Click(object sender, EventArgs e)
        {
            if (!confirmClearDetail())
                return;

            FindBillFrm frm = new FindBillFrm();
            //SelectBillFrm frm = new SelectBillFrm();
            frm.AllowMulitSelect = false;
            frm.SelectBillType = GRWL.BZSC.Common.EnumCommon.BillType.XQDD;
            //frm.SetCondition(GRWL.BZSC.Common.EnumCommon.BillType.XQDD, "", false);
            frm.BillPrefix = GRWL.BZSC.Common.EnumCommon.BillType.DH.ToString();
            frm.ShowDialog(this);
            if (frm.DialogResult == DialogResult.OK)
            {
                if (frm.SelectedItems != null)
                {

                    //QOrder order = frm.SelectedItems.Cast<QOrder>().First();
                    QOrder order = OTConverter.ConvertToObject<QOrder>(frm.SelectedItems);
                    this._OrderId = order.Id;
                    this._OrderCode = order.OrderCode;

                    int level = 1;
                    decimal? currentStock = this.BaseDataProxy.GetCurrentStock(order.MaterialId);
                    decimal num = 0;
                    if (order.Num != null)
                        num = Convert.ToDecimal(order.Num);
                    XMaterial xm = this.BaseDataProxy.GetXMaterial(order.MaterialId, null,null);
                    if (xm != null)
                    {
                        if (!xm.Material.isPurchase)//采购件不做生产
                        {
                            addDetailRow(null, level, order.Id, order.OrderCode, order.DetailId, order.MaterialId, order.MaterialCode, order.MaterialName, order.Specs,
                        order.PrjtId, order.PrjtCode, order.DetailMemo, num, num, DateTime.Now, DateTime.Now, xm.Material.source, xm.Material.department, xm.DepartmentName,
                        currentStock, currentStock, currentStock, num, num, order.Category, xm.Material.unit, xm.Material.isNominal, this.txtBoxCode.Text, this._Id, true, xm.Material.isNominal, num);
                            if (xm.Material.projectId != null)//产品主工程
                                addPrjtMaterials(level, Convert.ToInt32(xm.Material.projectId), num, order.Id, order.OrderCode);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 加载其他明细时询问是否清空原数据
        /// </summary>
        /// <returns></returns>
        private bool confirmClearDetail()
        {
            if (this.dataGridView1.Rows.Count > 0)
            {
                if (MessageBox.Show("是否重新运行生产需求计划，原有计划将被删除？", "系统提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    this.dataGridView1.Rows.Clear();
                    return true;
                }
                else
                { return false; }
            }
            return true;
        }

        /// <summary>
        /// 加载产品工程BOM材料
        /// </summary>
        /// <param name="pLevel"></param>
        /// <param name="prjtId"></param>
        /// <param name="pOrderNum"></param>
        private void addPrjtMaterials(int pLevel, int prjtId, decimal pOrderNum, int? orderId, string orderCode)
        {
            TB_ProductProject pp = this.BaseDataProxy.GetPrdtPrjt(prjtId);
            if (pp != null)
            {
                pLevel++;//层数累计
                XPrjtWorkstage[] pws = this.BaseDataProxy.FindPrjtWorkstages(pp.id);
                if (pws != null)
                {
                    foreach (XPrjtWorkstage pw in pws)
                    {
                        XPrjtElement[] pes = this.BaseDataProxy.FindPrjtElements(pw.PrjtWorkstage.id);
                        foreach (XPrjtElement pe in pes)
                        {
                            XMaterial material = this.BaseDataProxy.GetXMaterial(Convert.ToInt32(pe.PrjtElement.material), null,null);
                            if (material != null)
                            {
                                if (!material.Material.isPurchase)//采购件不做生产
                                {
                                    decimal num = 0;
                                    num = pOrderNum * pe.PrjtElement.dosage;

                                    decimal? currentStock = this.BaseDataProxy.GetCurrentStock(material.Material.id);

                                    addDetailRow(null, pLevel, orderId, orderCode, null, material.Material.id, material.Material.code, material.Material.cnName, material.Material.specs,
                                        pe.NextPrjtId, pe.NextPrjtCode, null, num, num, DateTime.Now, DateTime.Now, material.Material.source, material.Material.department, material.DepartmentName,
                                        currentStock, currentStock, currentStock, num, num, material.CategoryName, material.Material.unit, material.Material.isNominal, this.txtBoxCode.Text, this._Id,
                                        false, material.Material.isNominal, pOrderNum);
                                    if (pe.NextPrjtId != null)
                                        addPrjtMaterials(pLevel, Convert.ToInt32(pe.NextPrjtId), num, orderId, orderCode);
                                }
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 初始化操作按钮状态
        /// </summary>
        private void initBtns()
        {
            btnAppend.Enabled = (this.OperateType != Common.BillOperateType.Add) && (this.OperateType != Common.BillOperateType.Update);
            btnSave.Enabled = (this.OperateType == Common.BillOperateType.Add) || (this.OperateType == Common.BillOperateType.Update);
            btnRun.Enabled = (this.OperateType == Common.BillOperateType.Add) || (this.OperateType == Common.BillOperateType.Update);
            btnDelete.Enabled = (this.OperateType == Common.BillOperateType.Add) || (this.OperateType == Common.BillOperateType.Update);
            btnCorrect.Enabled = (this.OperateType == Common.BillOperateType.Add) || (this.OperateType == Common.BillOperateType.Update);
            btnDelItem.Enabled = (this.OperateType == Common.BillOperateType.Add) || (this.OperateType == Common.BillOperateType.Update);
            btnMaterial.Enabled = (this.OperateType == Common.BillOperateType.Add) || (this.OperateType == Common.BillOperateType.Update);
            btnConfirm.Enabled = this._EditMode;
            btnPrint.Enabled = (this.OperateType != Common.BillOperateType.Add) && (this.OperateType != Common.BillOperateType.Update);
        }

        private void btnAppend_Click(object sender, EventArgs e)
        {
            initAppend();
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
            {
                if (e.ColumnIndex == 10)
                {
                    _Rectangle = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); //得到所在单元格位置和大小
                    this._CbBoxPrjt.Size = new Size(_Rectangle.Width, _Rectangle.Height); //把单元格大小赋给时间控件
                    this._CbBoxPrjt.Location = new Point(_Rectangle.X, _Rectangle.Y); //把单元格位置赋给时间控件
                    this._CbBoxPrjt.Visible = true;
                }
                else if (e.ColumnIndex == 14 || e.ColumnIndex == 15) //判断所在是否日期选择的列
                {
                    _Rectangle = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); //得到所在单元格位置和大小
                    this._DTP.Size = new Size(_Rectangle.Width, _Rectangle.Height); //把单元格大小赋给时间控件
                    this._DTP.Location = new Point(_Rectangle.X, _Rectangle.Y); //把单元格位置赋给时间控件
                    this._DTP.Visible = true;  //可以显示控件了
                }
                else if (e.ColumnIndex == 16)
                {
                    _Rectangle = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); //得到所在单元格位置和大小
                    this._CbBox.Size = new Size(_Rectangle.Width, _Rectangle.Height); //把单元格大小赋给时间控件
                    this._CbBox.Location = new Point(_Rectangle.X, _Rectangle.Y); //把单元格位置赋给时间控件
                    this._CbBox.Visible = true;
                }
                else if (e.ColumnIndex == 18)
                {
                    _Rectangle = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); //得到所在单元格位置和大小
                    this._CbBoxDept.Size = new Size(_Rectangle.Width, _Rectangle.Height); //把单元格大小赋给时间控件
                    this._CbBoxDept.Location = new Point(_Rectangle.X, _Rectangle.Y); //把单元格位置赋给时间控件
                    this._CbBoxDept.Visible = true;
                }
                else
                {
                    this._DTP.Visible = false;
                    this._CbBox.Visible = false;
                    this._CbBoxDept.Visible = false;
                    this._CbBoxPrjt.Visible = false;
                }
            }
        }

        private void dataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            this._DTP.Visible = false;
            this._CbBox.Visible = false;
            this._CbBoxDept.Visible = false;
            this._CbBoxPrjt.Visible = false;
        }

        private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
        {
            this._DTP.Visible = false;
            this._CbBox.Visible = false;
            this._CbBoxDept.Visible = false;
            this._CbBoxPrjt.Visible = false;
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        /// <summary>
        /// 新增单据
        /// </summary>
        private void initAppend()
        {
            this.OperateType = Common.BillOperateType.Add;
            this._EditMode = false;
            this._Id = 0;
            clearForm();
            //this.txtBoxCode.Text = this.BaseDataProxy.GetSerialNo(1, this._RqrtType.ToString(), 4, true,true,true);
            this.txtBoxOperator.Text = SysLoginUserInfo.UserName;
            this.txtBoxOperator.Tag = SysLoginUserInfo.UserId;
            this.txtBoxDepartment.Text = SysLoginUserInfo.DepartmentName;
            this.txtBoxDepartment.Tag = SysLoginUserInfo.DepartmentId;
            this.dtpRqrtDate.Value = DateTime.Now;
        }

        /// <summary>
        /// 清除原单录入数据
        /// </summary>
        private void clearForm()
        {
            this.dtpRqrtDate.Value = DateTime.Now;
            this.dataGridView1.Rows.Clear();
            for (int i = 0; i < this.panel2.Controls.Count; i++)
            {
                if (this.panel2.Controls[i].Name.StartsWith("txtBox"))
                {
                    this.panel2.Controls[i].Text = string.Empty;
                    this.panel2.Controls[i].Tag = null;
                }
                else if (this.panel2.Controls[i].Name.StartsWith("ckBox"))
                {
                    CheckBox ckb = this.panel2.Controls[i] as CheckBox;
                    ckb.Checked = false;
                }
            }
        }

        /// <summary>
        /// 加载单据
        /// </summary>
        private void initEdit()
        {
            this._EditMode = true;
            this.OperateType = Common.BillOperateType.Update;
            this.dataGridView1.Rows.Clear();
            _XR = this.BaseDataProxy.GetXRequirement(this._Id);
            if (_XR != null)
            {
                this._OrderId = _XR.Requirement.orderId;
                this._OrderCode = _XR.Requirement.orderCode;

                GRWL.BZSC.Common.EnumCommon.VerifyStatus status = (GRWL.BZSC.Common.EnumCommon.VerifyStatus)Enum.Parse(typeof(GRWL.BZSC.Common.EnumCommon.VerifyStatus), this._XR.Requirement.status);
                initVerifyBtn(status);


                this.txtBoxOperator.Text = _XR.OperatorName;
                this.txtBoxOperator.Tag = _XR.Requirement.@operator;
                this.txtBoxAssessor.Text = _XR.AssessorName;
                this.txtBoxCode.Text = _XR.Requirement.code;
                this.txtBoxDepartment.Text = _XR.DepartmentName;
                this.txtBoxDepartment.Tag = _XR.Requirement.department;
                this.txtBoxMemo.Text = _XR.Requirement.memo;
                this.txtBoxMender.Text = _XR.MenderName;
                this.txtBoxStatus.Text = _XR.Requirement.status;
                this.txtBoxUpdateTime.Text = _XR.Requirement.updateTime.ToString();
                this.txtBoxVerifyTime.Text = _XR.Requirement.verifyTime.ToString();
                this.ckBoxIsRelease.Checked = _XR.Requirement.isRelease;
                this.ckBoxAdvance.Checked = _XR.Requirement.cAdvance;
                this.ckBoxCurrentStock.Checked = _XR.Requirement.cCurrentStock;
                this.ckBoxPlanProduction.Checked = _XR.Requirement.cPlanProduction;
                this.ckBoxPlanPurchase.Checked = _XR.Requirement.cPlanPurchase;
                this.ckBoxProducing.Checked = _XR.Requirement.cProducing;
                this.ckBoxPurchasing.Checked = _XR.Requirement.cPurchasing;
                this.ckBoxReceving.Checked = _XR.Requirement.cReceving;
                this.ckBoxSafeStock.Checked = _XR.Requirement.cSafeStock;
                this.ckBoxSaleDelivery.Checked = _XR.Requirement.cSaleDelivery;

                //加载明细数据
                XRqrtDetail[] xrds = this.BaseDataProxy.GetXRqrtDetails(new int[1] { _XR.Requirement.id });
                if (xrds != null)
                {
                    foreach (XRqrtDetail xrd in xrds)
                    {
                        addDetailRow(xrd.RqrtDetail.id, xrd.RqrtDetail.structlevel, xrd.RqrtDetail.orderId, xrd.RqrtDetail.orderCode, null, xrd.RqrtDetail.material,
                                xrd.RqrtDetail.materialCode, xrd.MaterialName, xrd.RqrtDetail.specs, xrd.RqrtDetail.prdtPrjtId, xrd.RqrtDetail.prdtPrjtCode, xrd.RqrtDetail.memo, xrd.RqrtDetail.hairNeeds,
                                xrd.RqrtDetail.netNeeds, xrd.RqrtDetail.rqrtDate, xrd.RqrtDetail.releaseDate, xrd.RqrtDetail.source, xrd.RqrtDetail.department, xrd.DepartmentName,
                                xrd.RqrtDetail.currentStock, xrd.RqrtDetail.safeStock, xrd.RqrtDetail.availableStock, xrd.RqrtDetail.planPurchase, xrd.RqrtDetail.planProduction, xrd.CategoryName, xrd.Unit,
                                xrd.RqrtDetail.isNominal, xrd.RqrtDetail.rqrtCode, this._Id, xrd.RqrtDetail.isMain, xrd.RqrtDetail.isRelease, xrd.RqrtDetail.orderNum);

                    }
                }
            }

        }

        private void initVerifyBtn(GRWL.BZSC.Common.EnumCommon.VerifyStatus status)
        {
            switch (status)
            {
                case GRWL.BZSC.Common.EnumCommon.VerifyStatus.未批:
                    this.tsmiPass.Enabled = true;
                    this.tsmiReturn.Enabled = true;
                    this.tsmiInvalid.Enabled = true;
                    this.tsmiDeVerify.Enabled = false;
                    break;
                case GRWL.BZSC.Common.EnumCommon.VerifyStatus.已批:
                    this.tsmiPass.Enabled = false;
                    this.tsmiReturn.Enabled = false;
                    this.tsmiInvalid.Enabled = false;
                    this.tsmiDeVerify.Enabled = true;
                    break;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否保存数据？", "系统提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            { }
            else
            {
                this.Close();
                return;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            save();
        }

        /// <summary>
        /// 单据保存
        /// </summary>
        private void save()
        {
            if (this.dataGridView1.Rows.Count < 1)
            {
                MessageBox.Show("单据不能没有明细数据！");
                return;
            }

            TB_Requirement rqrt = new TB_Requirement();
            rqrt.cAdvance = this.ckBoxAdvance.Checked;
            rqrt.cCurrentStock = this.ckBoxCurrentStock.Checked;
            rqrt.cPlanProduction = this.ckBoxPlanProduction.Checked;
            rqrt.cPlanPurchase = this.ckBoxPlanPurchase.Checked;
            rqrt.cProducing = this.ckBoxProducing.Checked;
            rqrt.cPurchasing = this.ckBoxPurchasing.Checked;
            rqrt.cReceving = this.ckBoxReceving.Checked;
            rqrt.cSafeStock = this.ckBoxSafeStock.Checked;
            rqrt.cSaleDelivery = this.ckBoxSaleDelivery.Checked;
            if (this.txtBoxDepartment.Tag != null)
                rqrt.department = Convert.ToInt32(this.txtBoxDepartment.Tag);
            rqrt.memo = this.txtBoxMemo.Text;
            rqrt.orderCode = this._OrderCode;
            rqrt.orderId = this._OrderId;
            rqrt.rqrtDate = this.dtpRqrtDate.Value;
            rqrt.type = this.RqrtType.ToString();

            if (this._EditMode)
            {
                if (this._XR.Requirement.status == GRWL.BZSC.Common.EnumCommon.VerifyStatus.已批.ToString())
                {
                    MessageBox.Show("已审批的单据不能修改！");
                    return;
                }

                rqrt.assessor = this._XR.Requirement.assessor;
                rqrt.code = this._XR.Requirement.code;
                rqrt.createTime = this._XR.Requirement.createTime;
                rqrt.deleteFlag = this._XR.Requirement.deleteFlag;
                rqrt.id = this._XR.Requirement.id;
                rqrt.isRelease = this._XR.Requirement.isRelease;
                rqrt.mender = SysLoginUserInfo.UserId;
                rqrt.@operator = this._XR.Requirement.@operator;
                rqrt.status = this._XR.Requirement.status;
                rqrt.updateTime = DateTime.Now;
                rqrt.verifyTime = this._XR.Requirement.verifyTime;

            }
            else
            {
                rqrt.code = this.BaseDataProxy.GetSerialNo((int)BZSC.Common.EnumCommon.CodeRuleType.Other, this.RqrtType.ToString(), 4, true, true, true); ;
                rqrt.createTime = DateTime.Now;
                rqrt.@operator = SysLoginUserInfo.UserId;
                rqrt.status = GRWL.BZSC.Common.EnumCommon.VerifyStatus.未批.ToString();
            }

            //绑定单据明细            
            List<TB_RqrtDetail> details = OTConverter.ConvertDgvToObjectList<TB_RqrtDetail>(this.dataGridView1, new string[] { }, null);
            if (details != null)
            {
                //foreach (TB_RqrtDetail d in details)
                //    d.rqrtCode = rqrt.code; 
                rqrt.TB_RqrtDetail = details.ToArray();
            }

            bool ok = false;
            int newId = 0;
            if (this._EditMode)
                ok = this.BaseDataProxy.UpdateRequirement(rqrt, true);
            else
            {
                newId = this.BaseDataProxy.AddRequirement(rqrt);
                ok = newId > 0;
                this.txtBoxCode.Text = rqrt.code;//存盘更新code显示
            }

            if (ok && rqrt.orderId != null)//更新原订单运行MRP状态
            {
                XOrder order = this.BaseDataProxy.GetXOrder(Convert.ToInt32(rqrt.orderId));
                if (order != null)
                {
                    order.Order.isMRP = true;
                    this.BaseDataProxy.UpdateOrder(order.Order, false);
                }
            }

            this.OperateType = Common.BillOperateType.View;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确认删除？", "系统提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                TB_Requirement rqrt = this._XR.Requirement;
                if (rqrt != null)
                {
                    if (rqrt.status == GRWL.BZSC.Common.EnumCommon.VerifyStatus.已批.ToString())
                    {
                        MessageBox.Show("已审批的单据不能删除！");
                        return;
                    }

                    if (this.BaseDataProxy.DeleteRequirement(rqrt.id))
                    {
                        this._EditMode = false;
                        this.OperateType = Common.BillOperateType.None;
                        clearForm();
                    }
                }
            }
        }

        /// <summary>
        /// 设置单据状态
        /// </summary>
        /// <param name="status"></param>
        private void setVerifyStatus(GRWL.BZSC.Common.EnumCommon.VerifyStatus status)
        {
            TB_Requirement rqrt = this._XR.Requirement;
            if (rqrt != null)
            {
                rqrt.status = status.ToString();
                DateTime d = DateTime.Now;
                rqrt.verifyTime = d;
                rqrt.assessor = SysLoginUserInfo.UserId;
                if (this.BaseDataProxy.UpdateRequirement(rqrt, false))
                {
                    initVerifyBtn(status);
                    this.txtBoxAssessor.Text = SysLoginUserInfo.UserName;
                    this.txtBoxAssessor.Tag = SysLoginUserInfo.UserId;
                    this.txtBoxVerifyTime.Text = d.ToString("yyyy-MM-dd hh:mm:ss");
                    this.txtBoxStatus.Text = rqrt.status;
                    this.OperateType = Common.BillOperateType.View;
                }
            }
        }

        /// <summary>
        /// 批准单据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiPass_Click(object sender, EventArgs e)
        {
            setVerifyStatus(GRWL.BZSC.Common.EnumCommon.VerifyStatus.已批);
        }

        /// <summary>
        /// 退回单据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiReturn_Click(object sender, EventArgs e)
        {
            setVerifyStatus(GRWL.BZSC.Common.EnumCommon.VerifyStatus.退回);
        }

        /// <summary>
        /// 作废单据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiInvalid_Click(object sender, EventArgs e)
        {
            setVerifyStatus(GRWL.BZSC.Common.EnumCommon.VerifyStatus.作废);
        }

        /// <summary>
        /// 反审批单据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiDeVerify_Click(object sender, EventArgs e)
        {
            setVerifyStatus(GRWL.BZSC.Common.EnumCommon.VerifyStatus.未批);
        }

        private void btnMaterial_Click(object sender, EventArgs e)
        {
            if (!confirmClearDetail())
                return;

            FindMaterialFrm frm = new FindMaterialFrm();
            frm.MutiSelect = true;
            frm.StockNullable = true;
            frm.ShowDialog(this);
        }

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            GRWL.BZSC.Common.EventCommon.FindMaterialUdDGVEvnt -= new GRWL.BZSC.Common.EventCommon.UpdateDataGridViewDlgt(updateFindMaterial);
        }

        private void btnDelItem_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.SelectedRows != null && this.dataGridView1.SelectedRows.Count > 0)
            {
                this.dataGridView1.Rows.Remove(this.dataGridView1.SelectedRows[0]);
            }
        }

        TextBox control = null;

        /// <summary>
        /// 在单元格编辑内容时触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            e.CellStyle.BackColor = Color.AliceBlue;//设置编译时的颜色
            control = (TextBox)e.Control;
            switch (this.dataGridView1.CurrentCell.ColumnIndex)
            {
                case 11:
                    control.Leave += new EventHandler(control_Leave);
                    break;
                case 13:
                    control.KeyPress += new KeyPressEventHandler(control_KeyPress);
                    break;
            }

        }

        /// <summary>
        /// 单元格输入框编辑内容按键事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void control_KeyPress(object sender, KeyPressEventArgs e)
        {
            ////限制只能输入0-9的数字，退格键，小数点
            if (this.dataGridView1.CurrentCell.ColumnIndex == 13)
            {
                if (((int)e.KeyChar >= 48 && (int)e.KeyChar <= 57) || e.KeyChar == 8 || e.KeyChar == 46)
                { }
                else
                    e.Handled = true;
            }
        }

        /// <summary>
        /// 单元格编辑离开时触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void control_Leave(object sender, EventArgs e)
        {
            //如果需要限制字符串输入长度
            if (control.Text.Length >= 3)
            {
                control.Focus();
            }
        }

        private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(this.dataGridView1);
        }

        private void dataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(this.dataGridView1);
        }
    }
}
